package com.mspbots.core.wise.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mspbots.core.AbstractBaseServiceImpl;
import com.mspbots.core.config.PropertiesConfiguration;
import com.mspbots.core.teams.model.Messages;
import com.mspbots.core.teams.model.TeamsUser;
import com.mspbots.core.teams.service.MessagesService;
import com.mspbots.core.teams.service.TeamsUserService;
import com.mspbots.core.wise.mapper.TenantReportMapper;
import com.mspbots.core.wise.model.Tenant;
import com.mspbots.core.wise.model.TenantReport;
import com.mspbots.core.wise.model.TenantUser;
import com.mspbots.core.wise.service.TenantReportService;
import com.mspbots.core.wise.service.TenantService;
import com.mspbots.core.wise.service.TenantUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * com.mspbots.core.service.impl.TenantReportServiceImpl
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2019/7/16
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class TenantReportServiceImpl extends AbstractBaseServiceImpl<TenantReportMapper, TenantReport>
        implements TenantReportService {

    private final TenantService tenantService;
    private final TenantUserService tenantUserService;
    private final JavaMailSender mailSender;
    private final PropertiesConfiguration.CoreProperties coreProperties;
    private final MessagesService messagesService;
    private final TeamsUserService teamsUserService;


    @Override
    public Boolean senderMail(TenantReport report) {
        List<TeamsUser> teamsUsers = teamsUserService.findAdminByTenantId(report.getTenantId());
        Messages messages = messagesService.getById(report.getMessageId());
        Tenant tenant = tenantService.getById(report.getTenantId());
        TenantUser tenantUser = tenantUserService.getOne(Wrappers.<TenantUser>lambdaQuery()
                .eq(TenantUser::getId, report.getTenantUserId())
                .eq(TenantUser::getTenantId, report.getTenantId()));
        Boolean result = this.saveOrUpdate(report);
        if (!StringUtils.isEmpty(tenantUser)) {
//            String receiver = "1785319835@qq.com";
            String receiver = tenantUser.getEmail();
            String receiverBCC = "c2905f5e.itsasap.com@amer.teams.ms";
            List<String> receiverCCList = new ArrayList<>();
            receiverCCList.add("ken.lee@jexet.com");
            receiverCCList.add("daniel.wang@itsasap.com");
            for (TeamsUser teamsUser : teamsUsers) {
                receiverCCList.add(teamsUser.getTeamsMail());
            }

            MimeMessagePreparator preparator = mimeMessage -> {
                mimeMessage.setRecipient(Message.RecipientType.TO,
                        new InternetAddress(receiver));
                mimeMessage.setRecipient(Message.RecipientType.BCC, new InternetAddress(receiverBCC));
//                mimeMessage.setRecipients(Message.RecipientType.CC,
//                        new Address[]{new InternetAddress(receiverCc)});
                if (receiverCCList != null) {
                    InternetAddress[] ccAddress = new InternetAddress[receiverCCList.size()];
                    for (int k = 0; k < receiverCCList.size(); k++) {
                        String emailAddress = receiverCCList.get(k);
                        ccAddress[k] = new InternetAddress(emailAddress);
                    }
                    mimeMessage.addRecipients(Message.RecipientType.CC, ccAddress);
                }
                mimeMessage.setFrom(new InternetAddress("support@mspbots.ai"));
                mimeMessage.setSubject("BugReport-" + report.getId() + " by \"" +
                        tenantUser.getFirstname() + " " + tenantUser.getLastname() + "\" from " + tenant.getShortName() + ". Server:Mspbots.ai");


                mimeMessage.setContent(report.getDocument() +
                                "<br><strong>Message Detail [" + report.getMessageId() + "]:</strong>" +
                                "<br>" + messages.getMessage(),
                        "text/html;charset=UTF-8");
            };

            try {
                this.mailSender.send(preparator);
            } catch (MailException ex) {
                log.error("Mail Sender to {} is error {}", tenantUser.getFirstname() + " "
                        + tenantUser.getLastname(), ex.getMessage());
            }
        }
        return result;
    }

    @Override
    public Page<TenantReport> page(Page<TenantReport> page, Wrapper<TenantReport> queryWrapper) {
        Page<TenantReport> reportPage = super.page(page, queryWrapper);
        reportPage.setRecords(reportPage.getRecords().parallelStream().peek(tenantReport -> {
            Tenant tenant = this.tenantService.getById(tenantReport.getTenantId());
            if (!ObjectUtils.isEmpty(tenant)) {
                tenantReport.setShortName(tenant.getShortName());
            }
            TenantUser tenantUser = this.tenantUserService.getById(tenantReport.getTenantUserId());
            if (!ObjectUtils.isEmpty(tenantUser)) {
                tenantReport.setTenantUserName(tenantUser.getFirstname() + " " + tenantUser.getLastname());
            }
        }).collect(Collectors.toList()));
        return reportPage;
    }
}
